<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="部门名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="department" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门" width="120" sortable>
			</el-table-column>
			<el-table-column prop="intro" type="textarea" label="部门简介" width="100" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父级部门" width="100" sortable>
			</el-table-column>
			<el-table-column prop="employee.username" label="管理人员" width="120" sortable>
			</el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: #13ce66">正常</span>
          <span v-else style="color: red">禁用</span>

        </template>
      </el-table-column>
      <el-table-column prop="path" label="path" width="120" sortable>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="update_time" label="修改时间" width="120" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          :current-page="query.page"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="query.total"
          style="float:right;">
      </el-pagination>
    </el-col>

		<!--工具条-->


		<!--新增/修改界面-->
		<el-dialog title="新增/修改" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="部门名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="父部门">
          <el-cascader v-model="addForm.parent"
                       :options="departmentTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="管理人员">
          <el-select v-model="addForm.employee" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" >
<!--          <el-input v-model="addForm.state" auto-complete="off"></el-input>-->
            <el-radio-group v-model="addForm.state">
              <el-radio class="radio" :label="1">正常</el-radio>
              <el-radio class="radio" :label="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="部门简介" prop="intro">
          <el-input type="textarea" v-model="addForm.intro" auto-complete="off">
          </el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {
			  //分页
				query: {
				pageSize:10,
				page: 1,
				total: 0,
        keyword:''
				},
        employees:[],
				department: [],
        departmentTree:[],
				listLoading: false,
				sels: [],//列表选中列

				departmentFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据->shuju
				addForm: {
				  id:null,
					name: '',
					intro:'',
          state:'',
          path:'',

          parent: {
					  id:null
          },
          employee: {
					  id:null,
            username:''
          }
				}

			}
		},
		methods: {
		  //获取部门树
		  getdepartmentTree(){
        //NProgress.start();
        this.$http.get("/department/tree")
            .then((res) => {
              res = res.data;
              console.log(res);
              if(res.success){
                this.query.total = res.result.total;
                this.departmentTree = res.result;
              }
            });

      },
      //高级查询
      search(){
        this.query.page = 1
        this.getDepartments();
      },
      handleCurrentChange(val){
        this.query.page = val;
        this.getDepartments()

      },
      //获取员工列表
      getEmployees(){
        //NProgress.start();
        this.$http.get("/employee")
            .then((res) => {
              res = res.data;
              console.log(res);
              if(res.success){
                this.query.total = res.result.total;
                this.employees = res.result;

              }
            });

      },

			//获取部门列表
			getDepartments() {
				// let para = this.query;
				this.listLoading = true;
				//NProgress.start();
       this.$http.post("/department",this.query)
           .then((res) => {
             console.log(this.query.keyword)
             res = res.data;
            console.log(res);
            if(res.success){
            this.query.total = res.result.total;
            this.department = res.result.datas;
            console.log(this.department)

            }
            this.listLoading = false;
					//NProgress.done();
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
          this.$http.delete("/department/"+row.id)
                    .then(result=>{
                      result = result.data;
                      if(result.success){
                        this.$message({ message: '删除成功', type: 'success' });
                        this.query.page = 1;
                        this.addLoading = false;
                        this.getDepartments();
                      }else{
                        this.$message({ message: '删除失败'+result.message, type: 'erro' });
                      }
                    })

				}).catch(() => {
          this.$message({ message: '已取消删除', type: 'info' });
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.getEmployees();
        this.getdepartmentTree();
        this.departmentFormVisible = true;
				this.addForm = Object.assign({}, row);
        //addForm里面的值没有进行连表查询,所以employee和parent的值是单独的属性,不是对象
        if(this.addForm.employee == null){
          this.addForm.employee={
            id:null
          };
        }
        //父级部门回显
        if(row.path != null){//path不等于空的时候->拿到他然后根据/分割
          let arrays = row.path.split("/");//分割以后是个数组,且字符串模式
          let ids = [];
          for (let i = 1;i < arrays.length-1;i++){
            ids.push(parseInt(arrays[i]));//往数组里面放值
          }
          this.addForm.parent = ids
        }
			},
			//显示新增界面
			handleAdd: function () {
				this.departmentFormVisible = true;
				this.addForm = {
				  id:null,
          name: '',
          intro:'',

          parent: {
            id:null
          },
          employee: {
            id:null,
          }
				};
				this.getEmployees();
				this.getdepartmentTree()
			},

			//新增
      save: function () {
        this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              this.addLoading = true;
              //NProgress.start();
              let para = Object.assign({}, this.addForm);
              // console.log(para.)
              //对parent进行一个判空,如果不为空的话需要将数据进行一个转化->部门下拉框
              if(para.parent != null){
                let array = para.parent;
                //在path中最后一个id才是他相应的父级部门
                para.parent = {id:array[array.length-1]};
              }
              this.$http.put("/department",para)
                  .then((result) => {
                    result = result.data;
                    if(result.success){
                      this.$message({  message: '提交成功', type: 'success' });
                      //成功以后要关闭模态框并刷新数据
                      this.addLoading = false;
                      this.departmentFormVisible = false;
                      this.query.page = 1;
                      this.getDepartments();
                    }else {
                      this.$message({  message: '提交失败'+result.message, type: 'success' });
                    }
                  })
            }).catch(() => {
          this.$message({message: '已取消删除', type: 'info'
          });
        });

			},
			selsChange: function (sels) {
				this.sels = sels;//获取整行数据
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				// console.log("ids:"+ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { ids: ids };
					this.$http.patch("/department",ids).then((res) => {
						this.listLoading = false;
						if(res.data.success){
						this.$message({ message: '删除成功', type: 'success' });

            }else {
              this.$message({ message: '删除失败'+res.data.message, type: 'error' });
            }
						//NProgress.done();
            this.query.page = 1;
						this.getDepartments();
					});
				}).catch(() => {
          this.$message({ message: '已取消删除', type: 'info' });
				});
			}
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>